#include<iostream>
#include<cstdlib>
#include<string>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

//子进程写入，父进程读取
int main()
{
    //1.创建管道 
    int fds[2] = {0};
    int n = ::pipe(fds);//输出行参数，交给fds
    if(n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return -1;
    }

    //2.创建子进程
    pid_t id = ::fork();
    if(id < 0)
    {
        std::cerr << "fork error" << std::endl;
    }
    else if(id == 0)
    {
        //子进程
        //3.关闭不需要的fd描述符-读端read
        ::close(fds[0]);

        int cnt = 0;
        int tot = 0;
        while(true)
        {
            std::string message = "h";
            // std::string message = "hello bit,hello  ";
            // //子进程pid转换为字符串
            // message += std::to_string(getpid());
            // message += ",";
            // message += std::to_string(cnt);

            //在子进程看来父进程就是个文件
            //将message的数据写到fds[1]里
            tot += ::write(fds[1],message.c_str(),message.size());
            cnt++;
            std::cout << "tot:" << tot << std::endl;
            sleep(2);
            //break;
        }
        exit(0);
    }
    else
    {
        //父进程
        //3.关闭不需要的fd描述符-写端write
        ::close(fds[1]);

        char buffer[1024];
        while(true)
        {
            sleep(1);

            //将读到的数据存放到数组里 
            ssize_t n = ::read(fds[0],buffer,1024);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "子进程发送来的数据:" << buffer <<std::endl;
            }
            else if(n == 0)
            {
                //如果写端关闭
                //读端读完管道内部的数据，在读取的时候，就会读取到返回值0，表示对端关闭，也表示读到文件结尾
                std::cout << "n:" << n << std::endl;
                std::cout << "子进程没有发送数据" << std::endl;
                break;
            }
            close(fds[0]);//关闭读端
            break;
            std::cout << "父进程已关闭" << std::endl;

        }
        int status = 0;//获取子进程退出信息
        pid_t rid = ::waitpid(id,&status,0);
        std::cout << "等待子进程:" << rid << "退出码：" << ((status<<8)&0xFF) <<
         "退出信号：" << (status & 0x7F) <<std::endl;
        
    }






    // std::cout << "ok" << std::endl;
    // std::cout << "ok" << std::endl;
    // std::cout << "ok" << std::endl;
    // std::cout << "ok" << std::endl;

    // std::cerr << "pipe error" << std::endl;
    // std::cerr << "pipe error" << std::endl;
    // std::cerr << "pipe error" << std::endl;
    // std::cerr << "pipe error" << std::endl;


    // if(n == 0)
    // {
    //     std::cout << "fds[0]:" << fds[0] << std::endl;
    //     std::cout << "fds[1]:" << fds[1] << std::endl;
    // }

    return 0;
}
